package com.car.loan.common.utils.file;

import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;


import com.car.loan.common.utils.BeanUtils;
import com.car.loan.project.xr.util.vo.pdf.SettlementPdf;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * @author huangding
 * @date 2020/3/19 20:04
 */
@Slf4j
public class PdfUtil {

    /**
     * 火狐处理
     */
    private static final String FIREFOX = "firefox";

    public static void downloadPdf(HttpServletResponse response,
        HttpServletRequest request, List<Object> settlementPdfList, String exportFileName,
        String templatePath)
        throws IOException, DocumentException {

        List<PdfReader> pdfReaders = new ArrayList<>(settlementPdfList.size());
        settlementPdfList.forEach(pdfBean -> {
            try {
                Map<String, Object> map = BeanUtils.javabean2map(pdfBean);
                PdfReader reader;
                PdfStamper stamper;
                try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
                    //读取pdf模板
                    reader = new PdfReader(templatePath);
                    stamper = new PdfStamper(reader, bos);
                    AcroFields form = stamper.getAcroFields();
                    for (String name : form.getFields().keySet()) {
                        Object o = map.get(name);
                        if (null != o) {
                            form.setField(name, o.toString());
                        }
                    }
                    //如果为false那么生成的PDF文件还能编辑，一定要设为true
                    stamper.setFormFlattening(true);
                    stamper.close();
                    reader = new PdfReader(bos.toByteArray());
                    pdfReaders.add(reader);
                } catch (IOException | DocumentException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

        Document document = new Document();
        PdfCopy copy = new PdfCopy(document, response.getOutputStream());
        document.open();
        for (PdfReader pdfReader : pdfReaders) {
            document.newPage();
            copy.addDocument(pdfReader);
        }
        copy.close();
        response.setHeader("Content-Type", "application/pdf");
        String fileName = URLEncoder.encode(exportFileName, "UTF-8");
        String userAgent = request.getHeader("USER-AGENT").toLowerCase();
        if (userAgent.contains(FIREFOX)) {
            fileName = new String((exportFileName).getBytes(UTF_8),
                ISO_8859_1);
        }
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.setHeader("Access-Control-Allow-Origin", "*");
    }
}
